package com.demo.common.utils;

import com.demo.common.constant.JWTConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
public class TokenManager {
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 刷新令牌 token 时间
     */
    @Async
    public void flushTokenTime(String token,Boolean rememberMe){
        // 获取当前令牌 token 剩余失效时长
        Long expireIn = redisTemplate.getExpire(JWTConstants.JWT_REDIS_KEY_PREFIX + token);
        // 判断是否选中 ‘记住我’
        if (rememberMe){
            // 选中 ，判断剩余失效时间小于预阀值
            if(expireIn<JWTConstants.JWT_REDIS_REMEMBER_THRESHOLD){
                redisTemplate.opsForValue().set(JWTConstants.JWT_REDIS_KEY_PREFIX+token,"",
                        Duration.ofSeconds(JWTConstants.JWT_REDIS_REMEMBER_EXPIRE_IN));
            }
        }else {
            // 未选中 ，判断剩余失效时间小于预阀值
            if (expireIn<JWTConstants.JWT_REDIS_EXPIRE_THRESHOLD){
                redisTemplate.opsForValue().set(JWTConstants.JWT_REDIS_KEY_PREFIX+token,"",
                        Duration.ofSeconds(JWTConstants.JWT_REDIS_EXPIRE_IN));
            }
        }
    }
}
